package org.vision.contactsmanager;

import org.vision.contactsmanager.bean.MyConstant;
import org.vision.contactsmanager.bean.MyContacts;
import org.vision.contactsmanager.dao.ContactsManagerDbAdater;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ExpandableListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.CursorTreeAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;

public class ContactsManager extends ExpandableListActivity {

    public static final String TAG = "ContactsManager";
    private ContactsManagerDbAdater contactsManagerDbAdapter;
    int groupNameIndex;
    private MyCursrTreeAdapter myCursorTreeAdapter;

    View view;
    PopupWindow pop;

    Button btnSms;
    Button btnEmail;
    Button btnCall;

    //上面搜索按钮，点击弹出新的搜索页面
    Button searchContactsBtn;

    //缓存除了所选联系人所在组的所有组，用在移动联系人上
    String groups[];

    //缓存用户所在的组,用在移动联系人上
    String mygroupName;

    //关于和帮助的菜单
    public static final int MENU_HELP = Menu.FIRST;
    public static final int MENU_ABOUT = Menu.FIRST + 1;

    //长按分组上的 菜单
    public static final int MENU_GROUP_ADD = Menu.FIRST;
    public static final int MENU_GROUP_DELETE = Menu.FIRST + 1;
    public static final int MENU_GROUP_MODIFY = Menu.FIRST + 2;
    public static final int MENU_GROUP_ADDCONTACT = Menu.FIRST + 3;

    //长按联系人菜单
    public static final int MENU_CONTACTS_DELETE = Menu.FIRST;
    public static final int MENU_CONTACTS_MODIFY = Menu.FIRST + 1;
    public static final int MENU_CONTACTS_MOVE = Menu.FIRST + 2;

    //联系人各个字段索引
    private static final int contactsContractId_index = 1;
    private static final int icon_index = 2;
    private static final int name_index = 3;
    private static final int description_index = 4;
    private static final int telPhone_index = 5;
    private static final int email_index = 6;

    //组上groupName字段索引
    private static final int groupName_index = 1;

    Cursor groupCursor;
    //初始化LODA联系人数据的弹出框
    private static final int DIALOG_KEY = 0;
    private static final int DIALOG_HELP = 1;
    private static final int DIALOG_ABOUT = 2;

    @Override
    protected void onResume() {
        super.onResume();
        //在恢复的时候，默认展开第一个组
        ExpandableListView elv = getExpandableListView();
        //判断是否生成UI
        if (elv.getCount() != 0) {
            elv.expandGroup(0);
        }
    }

    /**
     * 获取所有的联系人数据
     */
    private void initAllContacts() {
        contactsManagerDbAdapter = new ContactsManagerDbAdater(this);
        //第一次获取本地通讯录
        contactsManagerDbAdapter.getContactsContract();
        contactsManagerDbAdapter.open();
    }

    /**
     * 初始化所有需要跟联系人数据相关的UI
     */
    private void initAllUiWithDatas() {
        initMyAdapter();

        //第一次进入的时候，默认展开第一个组
        ExpandableListView elv = getExpandableListView();
        //判断是否生成UI
        if (elv.getCount() != 0) {
            elv.expandGroup(0);
        }
    }

    //获取通讯录进程
    private class GetContactTask extends AsyncTask<String, String, String> {
        public String doInBackground(String... params) {
            initAllContacts();
            return "";
        }

        @Override
        protected void onPreExecute() {
            showDialog(DIALOG_KEY);
            //初始化各种组件
            initComponents();
            initListeners();
        }

        @Override
        public void onPostExecute(String Re) {
            initAllUiWithDatas();
            removeDialog(DIALOG_KEY);
        }
    }

    // 弹出"查看"对话框
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_KEY: {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("获取通讯录中...请稍候");
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            return dialog;
        }
        case DIALOG_HELP: {
            return buildDialogHelp(ContactsManager.this);
        }
        case DIALOG_ABOUT: {
            return buildDialogAbout(ContactsManager.this);
        }
        }
        return null;
    }

    private Dialog buildDialogHelp(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("帮助");
        builder.setMessage("添加联系人，添加、删除、重命名组请对分组栏进行长按，删除、编辑、移动联系人请对联系人长按。搜索联系人点右上角搜索按钮。");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        });
        return builder.create();

    }

    private Dialog buildDialogAbout(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("关于");
        builder.setMessage("愿景工作室，您有任何软件开发运营合作意向、疑问、意见或建议，欢迎联系我。商务联系：dengjie200@163.com  工作室QQ：532054105");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
               
            }
        });
        return builder.create();

    }

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏幕
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,
        //WindowManager.LayoutParams. FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        //实例化异步线程来获取通讯录
        new GetContactTask().execute("");
        //getExpandableListView().setBackgroundResource(R.drawable.default_bg);
        registerForContextMenu(getExpandableListView());
    }

    private void initComponents() {
        //初始化弹出框
        initPopupWindow();

        getExpandableListView().setCacheColorHint(0);//拖动时避免出现黑色
        getExpandableListView().setDivider(null);//去掉每项下面的黑线(分割线)

        //自定义下拉图标
        getExpandableListView().setGroupIndicator(getResources().getDrawable(R.drawable.expander_ic_folder));
        //绑定点击联系人是打电话
        getExpandableListView().setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                TextView phoneNumberTv = (TextView) v.findViewById(R.id.phoneNumber);
                Uri uri = Uri.parse("tel:" + phoneNumberTv.getText());
                Intent it = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(it);
                return true;
            }
        });
        //初始化界面按钮
        searchContactsBtn = (Button) this.findViewById(R.id.searchContactsBtn);
    }

    private void initListeners() {
        //初始化搜索按钮的单击事件监听器
        searchContactsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ContactsManager.this, SearchContacts.class);
                startActivity(intent);
            }
        });
    }

    @Override
    /**
     * menu.findItem(EXIT_ID);找到特定的MenuItem
     * MenuItem.setIcon.可以设置menu按钮的背景
     */
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_HELP, 0, "帮助");
        menu.add(0, MENU_ABOUT, 0, "关于");
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_HELP:
            actionClickMenuHelp();
            break;
        case MENU_ABOUT:
            actionClickMenuAbout();
            break;

        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 点击帮助menu的执行的动作
     */
    private void actionClickMenuHelp() {
        showDialog(MENU_HELP);
    }

    /**
     * 点击关于menu的执行的动作
     */
    private void actionClickMenuAbout() {
        showDialog(MENU_ABOUT);
    }

    private void initPopupWindow() {
        view = this.getLayoutInflater().inflate(R.layout.popup_window, null);
        pop = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setOutsideTouchable(true);
        btnSms = (Button) view.findViewById(R.id.btnSms);
        btnEmail = (Button) view.findViewById(R.id.btnEmail);
        btnCall = (Button) view.findViewById(R.id.btnCall);
    }

    //给适配器赋值，刷新界面的时候也会用到
    public void initMyAdapter() {
        groupCursor = contactsManagerDbAdapter.getAllGroups();
        startManagingCursor(groupCursor);
        //get the groupName column index
        groupNameIndex = groupCursor.getColumnIndexOrThrow("groupName");

        //set my adapter
        myCursorTreeAdapter = new MyCursrTreeAdapter(groupCursor, this, true);
        setListAdapter(myCursorTreeAdapter);
    }

    public class MyCursrTreeAdapter extends CursorTreeAdapter {

        public MyCursrTreeAdapter(Cursor cursor, Context context, boolean autoRequery) {
            super(cursor, context, autoRequery);
        }

        @Override
        protected void bindGroupView(View view, Context context, Cursor cursor, boolean isExpanded) {
            // TODO Auto-generated method stub
            //Log.v(TAG, "bindGroupView");
            TextView groupName = (TextView) view.findViewById(R.id.groupName);
            String group = cursor.getString(groupName_index);
            groupName.setText(group);

            TextView groupCount = (TextView) view.findViewById(R.id.groupCount);
            int count = contactsManagerDbAdapter.getCountContactByGroupName(group);
            groupCount.setText("[" + count + "]");
        }

        @Override
        protected View newGroupView(Context context, Cursor cursor, boolean isExpanded, ViewGroup parent) {
            Log.v(TAG, "newGroupView");
            LayoutInflater inflate = LayoutInflater.from(ContactsManager.this);
            View view = inflate.inflate(R.layout.grouplayout, null);

            bindGroupView(view, context, cursor, isExpanded);

            return view;
        }

        @Override
        protected Cursor getChildrenCursor(Cursor groupCursor) {
            Log.v(TAG, "getChildrenCursor");
            String groupName = groupCursor.getString(groupName_index);//得到当前的组名
            Cursor childCursor = contactsManagerDbAdapter.getContactsByGroupName(groupName);
            startManagingCursor(childCursor);
            return childCursor;
        }

        @Override
        protected View newChildView(Context context, Cursor cursor, boolean isLastChild, ViewGroup parent) {
            Log.v(TAG, "newChildView");
            LayoutInflater inflate = LayoutInflater.from(ContactsManager.this);
            View view = inflate.inflate(R.layout.childlayout, null);

            bindChildView(view, context, cursor, isLastChild);

            return view;
        }

        @Override
        protected void bindChildView(View view, Context context, Cursor cursor, boolean isLastChild) {
            // TODO Auto-generated method stub
            Log.v(TAG, "bindChildView");
            ImageView contactIcon = (ImageView) view.findViewById(R.id.contactIcon);
            contactIcon.setImageBitmap(getBitmapFromByte(cursor.getBlob(icon_index)));

            TextView contactsCId = (TextView) view.findViewById(R.id.contactsCId);
            contactsCId.setText(cursor.getString(contactsContractId_index));

            TextView name = (TextView) view.findViewById(R.id.name);
            name.setText(cursor.getString(name_index));

            TextView description = (TextView) view.findViewById(R.id.description);
            description.setTextKeepState(cursor.getString(description_index));

            final String phoneNumber = cursor.getString(telPhone_index);
            TextView phoneNumberTv = (TextView) view.findViewById(R.id.phoneNumber);
            phoneNumberTv.setText(phoneNumber);
            final String email = cursor.getString(email_index);

            ImageView mycursor = (ImageView) view.findViewById(R.id.myCursor);
            mycursor.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //showToast("点击了图片");
                    if (pop.isShowing()) {
                        pop.dismiss();
                    } else {
                        pop.showAsDropDown(v);

                        btnSms.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                pop.dismiss();
                                Uri uri = Uri.parse("smsto:" + phoneNumber);
                                Intent it = new Intent(Intent.ACTION_SENDTO, uri);
                                it.putExtra("sms_body", "");
                                startActivity(it);
                            }
                        });

                        btnEmail.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                pop.dismiss();
                                Uri uri = Uri.parse("mailto:" + email);
                                Intent it = new Intent(Intent.ACTION_SENDTO, uri);
                                startActivity(it);
                            }
                        });

                        btnCall.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                pop.dismiss();
                                Uri uri = Uri.parse("tel:" + phoneNumber);
                                Intent it = new Intent(Intent.ACTION_DIAL, uri);
                                startActivity(it);
                            }
                        });
                    }
                }
            });
        }
    }

    //得到存储在数据库中的头像
    public Bitmap getBitmapFromByte(byte[] temp) {
        if (temp != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        } else {
            return getNullIcon();
        }
    }

    //得到没有设置头像的QQ企鹅图片
    public Bitmap getNullIcon() {
        Resources res = getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.h001);
        return bmp;
    }

    //弹出提示信息
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;

        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {//在组上长按
            String title = ((TextView) info.targetView.findViewById(R.id.groupName)).getText().toString();
            menu.setHeaderTitle(title);
            menu.add(0, MENU_GROUP_ADD, 0, "添加分组");
            menu.add(0, MENU_GROUP_DELETE, 0, "删除分组");
            menu.add(0, MENU_GROUP_MODIFY, 0, "重命名");
            menu.add(0, MENU_GROUP_ADDCONTACT, 0, "添加联系人");

        } else if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {//在联系人上长按
            String title = ((TextView) info.targetView.findViewById(R.id.name)).getText().toString();
            Drawable icon = ((ImageView) info.targetView.findViewById(R.id.contactIcon)).getDrawable();
            menu.setHeaderTitle(title);
            menu.setHeaderIcon(icon);
            menu.add(0, MENU_CONTACTS_DELETE, 0, "删除联系人");
            menu.add(0, MENU_CONTACTS_MODIFY, 0, "编辑联系人");
            menu.add(0, MENU_CONTACTS_MOVE, 0, "移动联系人到...");
        }

    }

    public boolean onContextItemSelected(MenuItem item) {

        ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();
        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
            final String name = ((TextView) info.targetView.findViewById(R.id.name)).getText().toString();
            final String contactsContractId = ((TextView) info.targetView.findViewById(R.id.contactsCId)).getText()
                    .toString();
            switch (item.getItemId()) {
            case MENU_CONTACTS_DELETE: {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("确定要删除联系人吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MyContacts mc = new MyContacts();
                        mc.setContactsContractId(contactsContractId);
                        mc.setName(name);
                        contactsManagerDbAdapter.deleteDataFromContacts(mc);
                        initMyAdapter();
                        showToast("删除成功");
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                });
                builder.show();
                break;
            }
            case MENU_CONTACTS_MODIFY: {
                Intent intent = new Intent();
                intent.putExtra("name", name);
                intent.setAction(Intent.ACTION_EDIT);
                intent.setDataAndType(Uri.parse(MyConstant.CONTENT_URI), MyConstant.CONTENT_TYPE_EDIT);
                startActivity(intent);
                break;
            }
            case MENU_CONTACTS_MOVE:
                createMoveContactDialog(name).show();
                break;
            }

            return true;
        } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
            String groupName = ((TextView) info.targetView.findViewById(R.id.groupName)).getText().toString();
            switch (item.getItemId()) {
            case MENU_GROUP_ADD:
                createDialog("addGroup", groupName).show();
                break;
            case MENU_GROUP_DELETE:
                createDialog("deleteGroup", groupName).show();
                break;
            case MENU_GROUP_MODIFY:
                createDialog("modifyGroup", groupName).show();
                break;
            case MENU_GROUP_ADDCONTACT: {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_INSERT);
                intent.setDataAndType(Uri.parse(MyConstant.CONTENT_URI), MyConstant.CONTENT_TYPE_INSERT);
                startActivity(intent);
                break;
            }
            }

            return true;
        }
        return false;

    }

    private Dialog createMoveContactDialog(final String name) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("移动联系人到...");
        builder.setSingleChoiceItems(getSpecAllGroup(name), -1, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //得到用户要移动到的组
                String newgroupName = groups[which];
                String sql = "update contacts set groupName=? where groupName=? and name=?";
                Object[] Args = {newgroupName, mygroupName, name};
                contactsManagerDbAdapter.updateSyncData(sql, Args);
                initMyAdapter();
                showToast("成功移动联系人到" + newgroupName);
                dialog.dismiss();
            }
        });
        return builder.create();
    }

    private String[] getSpecAllGroup(String name) {
        String sql = "select groupName from contacts where name=?";
        String selectionArgs[] = {name};
        mygroupName = contactsManagerDbAdapter.checkContactGroup(sql, selectionArgs);
        Cursor cursor = contactsManagerDbAdapter.getAllGroups();
        int count = cursor.getCount() - 1;
        groups = new String[count];
        int i = 0;
        while (cursor.moveToNext()) {
            String newgroupName = cursor.getString(1);
            if (!newgroupName.equals(mygroupName)) {
                groups[i] = newgroupName;
                i++;
            }
        }
        cursor.close();
        return groups;
    }

    private Dialog createDialog(String msg, final String groupName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (msg.equals("addGroup")) {
            final EditText content = new EditText(this);
            builder.setTitle("添加组");
            builder.setView(content);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //添加新的组到数据库
                    String groupName = content.getText().toString().trim();
                    Cursor cursor = contactsManagerDbAdapter.getAllGroups();
                    if (!groupName.equals("")) {
                        while (cursor.moveToNext()) {
                            if (cursor.getString(1).equals(groupName)) {
                                showToast(groupName + "已存在！");
                                return;
                            }
                        }
                        contactsManagerDbAdapter.inserDataToGroups(groupName);
                        initMyAdapter();
                        showToast("添加成功");
                    }
                }
            });
            builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                }
            });
            return builder.create();
        }
        if (msg.equals("deleteGroup")) {
            builder.setTitle("确定要删除该组和该组内的所有联系人吗?");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    contactsManagerDbAdapter.deleteDataFromGroups(groupName);
                    String sql = "delete from contacts where groupName=?";
                    Object Args[] = {groupName};
                    contactsManagerDbAdapter.updateSyncData(sql, Args);
                    initMyAdapter();
                    showToast("删除成功");
                }
            });
            builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            return builder.create();
        }
        if (msg.equals("modifyGroup")) {
            final EditText content = new EditText(this);
            content.setText(groupName);
            builder.setTitle("请输入新的组名");
            builder.setView(content);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String newgroupName = content.getText().toString().trim();
                    Cursor cursor = contactsManagerDbAdapter.getAllGroups();
                    if (!newgroupName.equals("")) {
                        while (cursor.moveToNext()) {
                            if (cursor.getString(1).equals(newgroupName)) {
                                if (!newgroupName.equals(groupName)) {
                                    showToast(newgroupName + "已存在");
                                    return;
                                } else {
                                    return;
                                }
                            }
                        }
                        contactsManagerDbAdapter.updateDataToGroups(newgroupName, groupName);
                        String sql = "update contacts set groupName=? where groupName=?";
                        Object Args[] = {newgroupName, groupName};
                        contactsManagerDbAdapter.updateSyncData(sql, Args);
                        initMyAdapter();
                        showToast("修改成功");
                    }
                }
            });
            builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            return builder.create();
        }
        return null;
    }

    //处理键盘事件
    /*public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("确定要退出程序?");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                    finish();
                }
            });
            builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });
            builder.show();
            return true;
        } else {

            return super.onKeyDown(keyCode, event);
        }
    }
    */
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (contactsManagerDbAdapter != null) {
            contactsManagerDbAdapter.close();
            contactsManagerDbAdapter = null;
        }
    }
}